package cn.mesmile.lock.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zb
 * @date 2020/12/4 11:32
 * @Description
 */
@RequestMapping("/api/v1/session")
@RestController
public class SessionController {

    @GetMapping("/setSession")
    public Map<String, Object> setSession(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        HttpSession session = request.getSession();

        session.setAttribute("request url", request.getRequestURL());

        map.put("request url", request.getRequestURL());
        map.put("request sessionId", session.getId());

        return map;
    }

    @GetMapping("/getSession")
    public Map<String, Object> getSession(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("sessionIdUrl", request.getSession().getAttribute("request url"));
        map.put("sessionId", request.getSession().getId());
        return map;
    }

    @RequestMapping("/test")
    public String cookie(HttpServletRequest request) {
        HttpSession session = request.getSession();

        Object attribute = session.getAttribute("keyword");
        if(attribute == null) {
            System.out.println(">>>>>>>>>>>> 不存在session，设置keyword= ："+ request.getLocalAddr());
            session.setAttribute("keyword", request.getLocalAddr());
        } else {
            System.out.println(">>>>>>>>>>>> 不存在session，keyword= ："+ attribute.toString());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName()+"   :  "+ cookie.getValue());
            }
        }
        return "index";
    }



}
